import axios, { AxiosInstance, AxiosRequestConfig, AxiosResponse } from "axios";
import { message } from 'ant-design-vue';
interface requestType {
  url: string
  params?: any
}
const handleCode = async (code: number, msg: string) => {
  switch (code) {
    case 401:
        message.error(msg || '登录失效')
      setTimeout(() => {
        console.log('登录失效')
      }, 1500)
      // 跳转登录
      break
    default:
        message.error(msg || `后端接口${code}异常`)
      break
  }
}



//创建axsio 赋给常量service
const service: AxiosInstance = axios.create({
  baseURL:import.meta.env.VITE_API_BASE_URL,
   timeout:30000,
   headers: {
    'Content-Type': 'application/json;charset=UTF-8',
  }
});
// 添加请求拦截器
service.interceptors.request.use(
   (config: any)=> {
    console.log(config,'config')
    return config;
  },
   (error:any)=> {
    // 对请求错误做些什么
    console.log(error,'error')
    return Promise.reject(error);
  }
);
// 添加响应拦截器
service.interceptors.response.use(
   (response: AxiosResponse)=> {
    //response参数是响应对象
    // 对响应数据做点什么
    const { data, config } = response
    return data;
  },
   (error:any)=> {
    const { response} = error
   
    if (error.response && error.response.data) {
      const { status, data } = response
      handleCode(status, data.msg)
     
    // 对响应错误做点什么
    return Promise.reject(error);
    }else {
      let { message } = error
      if (message === 'Network Error') {
        message = '后端接口连接异常'
      }
      if (message.includes('timeout')) {
        message = '后端接口请求超时'
      }
      if (message.includes('Request failed with status code')) {
        const code = message.substr(message.length - 3)
        message = '后端接口' + code + '异常'
      }
      message.error(message || `后端接口未知异常`)
      return Promise.reject(error);
    }
  }
);





/**
 * @description GET
 */
 const GET = (data: requestType) => {
  return service.get(data.url, data.params)
}

/**
 * @description POST
 */
 const POST = (data: requestType) => {
  return service.post(data.url, data.params)
}
/**
 * @description PUT
 */
 const PUT = (data: requestType) => {
  return service.put(data.url, data.params)
}

/**
 * @description DELETE
 */
const DELETE = (data: requestType) => {
  return service({
    url: data.url,
    method: 'delete',
    data: data.params,
  } as AxiosRequestConfig)
}

/**
 * @description PATCH
 */
const PATCH = (data: requestType) => {

  return new Promise((resolve, reject) => {
    service
      .put(data.url, data.params)
      .then((res: any) => {
        if (res && res.status == 200) {
          resolve(res)
        }
      })
      .catch((error: any) => {
        reject(error)
      })
  })
}
export { GET, POST, PUT, DELETE, PATCH }

